package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.repository.*;
import com.hualude.roadsign.service.SignalLampFaultService;
import com.hualude.roadsign.utils.PushUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by pjn on 2017/8/5.
 */
@Service
public class SignalLampFaultServiceImpl implements SignalLampFaultService {
    @Resource
    private SignalLampFaultRepository signalLampFaultRepository;
    @Resource
    private SignalLampRepository signalLampRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private OrgRepository orgRepository;
    @Resource
    private PushHistoryRepository pushHistoryRepository;

    private String strUserIds;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public DTResponseDto getLampReportFault4DT(DTRequestDto dtRequestDto, Integer actorId, Integer userId, Integer orgId) throws Exception {
        Integer count;
        List<DTLampFaultDto> dto4DTs;
        count = signalLampFaultRepository.getLampReportFaultCount4DT(actorId, userId, orgId, dtRequestDto.getSearch());
        dto4DTs = signalLampFaultRepository.getLampReportFault4DT(dtRequestDto, actorId, userId, orgId);
        for (DTLampFaultDto dto : dto4DTs) {
            dto.setLampCheckerName(userRepository.getUserNameByUserId(dto.getLampCheckerId()));
        }
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    @Transactional
    public Integer updateSignalLampFault(Integer lampFaultId, Integer lampLevel, Integer lampType, String lampPhoto, String lampReason, Double lampMoney) throws Exception {
        return signalLampFaultRepository.updateSignalLampFault(lampFaultId, lampLevel, lampType, lampPhoto, lampReason, lampMoney);
    }

    @Transactional
    public Integer deleteLampFaultByIds(String lampFaultIds) throws Exception {
        String[] faultIdArray = lampFaultIds.split(",");
        int i = 0;
        for (i = 0; i < faultIdArray.length; i++) {
            signalLampFaultRepository.deleteLampFaultByIds(Integer.parseInt(faultIdArray[i]));
        }
        return i;
    }

    public List<SignalLampFaultDto> getLampCoordinate4Map(Integer orgId, Integer actorId) throws Exception {
        return signalLampRepository.getLampCoordinate4Map(orgId, actorId);
    }

    public List<SignalLampFaultDto> getLampEnergyByXY(String longitude, String latitude) throws Exception {
        return signalLampRepository.getLampEnergyByXY(longitude, latitude);
    }

    public List<String> getStartRoad(String roadName, Integer actorId, Integer orgId) throws Exception {
        return signalLampRepository.getStartRoad(roadName, actorId, orgId);
    }

    public List<String> getSectionByStartRoad(String roadName, Integer actorId, Integer orgId) throws Exception {
        return signalLampRepository.getSectionByStartRoad(roadName, actorId, orgId);
    }

    public Integer reportLampFault(final Integer signalLampId, Integer lampCreatorId, Integer lampLevel, Integer lampType,
                                   String lampPhoto, String lampReason, Double lampMoney, final Integer lampOrgId, Integer lampMainOrgId) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if (lampMoney == null)
            lampMoney = 0.0;
        SignalLampFaultDto insertDto = new SignalLampFaultDto();
        insertDto.setSignalLampId(signalLampId);
        insertDto.setLampCreatorId(lampCreatorId);
        insertDto.setLampLevel(lampLevel);
        insertDto.setLampType(lampType);
        insertDto.setLampTime(df.format(new Date()));
        insertDto.setLampPhoto(lampPhoto);
        insertDto.setLampReason(lampReason);
        insertDto.setLampMoney(lampMoney);
        insertDto.setLampOrgId(lampOrgId);
        insertDto.setLampMainOrgId(lampMainOrgId);

        List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(lampOrgId, 3);
        final String msg = "信号灯 NO：" + signalLampId + " 待审核";
        strUserIds = "";
        for (UserDto userDto : userDtos) {
            strUserIds += userDto.getUserId().toString() + ",";
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!strUserIds.equals("")) {
                        strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                        PushUtil.sendPushToUser(strUserIds, msg);
                        PushHistoryDto pushHistoryDto = new PushHistoryDto(lampOrgId, 3, msg, formatter.format(new Date()),2);
                        pushHistoryRepository.save(pushHistoryDto.toBean());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return signalLampFaultRepository.save(insertDto.toBean()).getLampFaultId();
    }

    public Integer getLampFaultIsReport(Integer signalLampId) throws Exception {
        List<SignalLampFaultDto> signalLampFaultDtos = signalLampFaultRepository.getLampFaultIsReport(signalLampId);
        Integer result = 1;
        if (signalLampFaultDtos.size() != 0) {
            Integer mainCheck = signalLampFaultDtos.get(0).getLampMainCheck();
            Integer check = signalLampFaultDtos.get(0).getLampCheck();
            Integer status = signalLampFaultDtos.get(0).getLampMaintenanceStatus();
            if (status == 2) {
                result = 1;//维修完成
            } else if (mainCheck == -1 || check == -1) {
                result = 1;//
            } else {
                result = 0;
            }
        }
        return result;
    }

    public DTResponseDto getLampFaultReport4DT(DTRequestDto dtRequestDto, Integer actorId, Integer orgId, String signalLampStartRoad, String signalLampEndRoad) throws Exception {
        if (signalLampStartRoad.equals("") && signalLampEndRoad.equals("")) {
            return new DTResponseDto(dtRequestDto.getDraw(), 0, 0, "");
        } else {
            List<SignalLampFaultDto> dto4DTs = signalLampRepository.getLampFaultReport4DT(dtRequestDto, actorId, orgId, signalLampStartRoad, signalLampEndRoad);
            for (SignalLampFaultDto dto : dto4DTs) {
                List<SignalLampFaultDto> signalLampFaultDtos = signalLampFaultRepository.getLampFaultIsReport(dto.getSignalLampId());
                Integer result = 1;
                if (signalLampFaultDtos.size() != 0) {
                    Integer mainCheck = signalLampFaultDtos.get(0).getLampMainCheck();
                    Integer check = signalLampFaultDtos.get(0).getLampCheck();
                    Integer status = signalLampFaultDtos.get(0).getLampMaintenanceStatus();
                    if (status == 2) {
                        result = 1;//维修完成
                    } else if (mainCheck == -1 || check == -1) {
                        result = 1;//
                    } else {
                        result = 0;
                    }
                }
                dto.setReportStatus(result);
            }
            DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), 1, 1, dto4DTs);
            return dtResponseDto;
        }
    }

    public List<SignalLampFaultDto> getLampFaultReportList4App(Integer orgId, String actorIds, Integer faultStatus, Integer count, Integer size) throws Exception {
        return signalLampFaultRepository.getLampFaultReportList4App(orgId,actorIds,faultStatus,count,size);
    }
}
